package com.imist.PipelineAndChannelHandler.server;


import com.imist.PipelineAndChannelHandler.protocol.Packet;
import com.imist.PipelineAndChannelHandler.protocol.PacketCodeC;
import com.imist.PipelineAndChannelHandler.protocol.request.LoginRequestPacket;
import com.imist.PipelineAndChannelHandler.protocol.request.MessageRequestPacket;
import com.imist.PipelineAndChannelHandler.protocol.response.LoginResponsePacket;
import com.imist.PipelineAndChannelHandler.protocol.response.MessageResponsePacket;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Date;


public class ServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        ByteBuf requestByteBuf = (ByteBuf) msg;
        Packet packet = PacketCodeC.INSTANCE.decode(requestByteBuf);

        //判断是否是登陆请求的数据包
        if (packet instanceof LoginRequestPacket){
            System.out.println(new Date() + ": 客户端开始登录……");
            LoginRequestPacket loginRequestPacket = (LoginRequestPacket) packet;
            LoginResponsePacket loginResponsePacket = new LoginResponsePacket();
            loginResponsePacket.setVersion(packet.getVersion());
            //登陆校验
            if (valid(loginRequestPacket)){
                //校验成功
                loginResponsePacket.setSuccess(true);
                System.out.println(new Date() + ": 登录成功!!!");
            }else {
                //校验失败
                loginResponsePacket.setSuccess(false);
                loginResponsePacket.setReason("账号密码校验失败...");
                System.out.println("登录失败");
            }
            //编码
            ByteBuf responseBytebuf = PacketCodeC.INSTANCE.encode(ctx.alloc(),loginResponsePacket);
            ctx.channel().writeAndFlush(responseBytebuf);
        }else if (packet instanceof MessageRequestPacket){
            //处理消息
            MessageRequestPacket messageRequestPacket = (MessageRequestPacket) packet;
            System.out.println(new Date() +" : 收到客户端消息 :" +messageRequestPacket.getMessage());
            MessageResponsePacket messageResonsePacket = new MessageResponsePacket();
            messageResonsePacket.setMessage( "服务端回复: ["+messageRequestPacket.getMessage()+ "]");
            ByteBuf responseByteBuf = PacketCodeC.INSTANCE.encode(ctx.alloc(),messageResonsePacket);
            ctx.channel().writeAndFlush(responseByteBuf);

        }
    }

    private boolean valid(LoginRequestPacket loginRequestPacket) {
        return true;
    }
}
